//
//  StatsV2ViewController.m
//  Fuel Log 4
//
//  Created by Olaf on 22.05.10.
//  Copyright 2010 olafgreck. All rights reserved.
//

#import "StatsV2ViewController.h"
#import "PrefsV2ViewController.h"
#import "Plot.h"
#import "FuelLogAppDelegate.h"
#import "FuelLogViewController.h"
#import "Car.h"
#import "Gas.h"

#import "DebugOutput.h"

#define stats_NumberofSections			3	// total sections in UITableView

// section Setup
#define stats_SectionSetup					0	// first section
#define stats_NumberOfRowsSectionSetup	3	// has three rows
#define stats_ObservationPeriod			0	// call sub-viewController
#define stats_BeginDate						1  // beginDate
#define stats_EndDate						2	// endDate

// section Results in text form
#define stats_SectionData					1
#define stats_NumberOfRowsSectionData	5

#define stats_Distance				0	// distanceString
#define stats_Volume					1	// volumeString 
#define stats_Consumption			2	// consumptionString
#define stats_Cost					3	// costString
#define stats_CostPerDistance		4	// costDistanceString


// section graphics

#define stats_SectionView					2
#define stats_NumberOfRowsSectionView	2

#define stats_SectionView_RowPlot		0	//placeholder for row number 
#define stats_SectionView_RowBar			1





@implementation StatsViewController

@synthesize preferencesPrimaryArray;
@synthesize preferencesSecondaryArray;
@synthesize preferencesTitleArray;
@synthesize beginIdx, endIdx, fillCount;

@synthesize dateString, beginDate, endDate;
@synthesize beginDateString, endDateString;
@synthesize doneButton;  
@synthesize distanceString, volumeString;
@synthesize consumptionString, costString, unitCostString, costDistanceString ;


#pragma mark -
#pragma mark -
#pragma mark UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (buttonIndex == [alert cancelButtonIndex]) {
		return;
	}
}



#pragma mark -
- (IBAction)done:(id)sender {  
//	debug(@"in done"); 
	 [self.navigationController popViewControllerAnimated:YES];
	  
}

-(void)showErrorText:(NSString *)errorText {
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Test"
													message:errorText
												   delegate:nil
										  cancelButtonTitle:@"OK"
										  otherButtonTitles: nil];
	[alert show];
	[alert release];
}

#pragma mark -
#pragma mark Calculations and stuff
- (void)setBoxes {
	FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	[self setDistanceString:[FuelLogAppDelegate pref].distanceText];
	[self setVolumeString:[FuelLogAppDelegate pref].fuelText];
	[self setConsumptionString:[FuelLogAppDelegate pref].dpfText];
	[self setCostDistanceString:[FuelLogAppDelegate pref].cpdText];
	
	
	NSDateFormatter *formatter = [FuelLogAppDelegate pref].dateFormatter;
	if (endDate == [endDate earlierDate:beginDate]) {
		NSDate *temp = endDate;
		//		[self setEndDate:beginDate];
		//		[self setBeginDate:temp];
		endDate = beginDate;
		beginDate = temp;
	}
	[self setBeginDateString:[formatter stringFromDate:beginDate]];
	[self setEndDateString:[formatter stringFromDate:endDate]];
#pragma mark - begin chart Calculations
	
//	int beginIdx, endIdx, 
//	int 
	fillCount = 0;
	float totalDistance = 0.0, totalFuel = 0.0, totalCost = 0.0, dpf = 0.0, cpd = 0.0;
	for (beginIdx = appDelegate.pumps.count - 1; beginIdx >= 0; --beginIdx) {
		Gas *gas = (Gas *)[appDelegate.pumps objectAtIndex:beginIdx];
		NSComparisonResult comp = [beginDate compare:gas.date];
		if (comp == NSOrderedSame || comp == NSOrderedAscending) break;
	}
	for (endIdx = 0; endIdx < appDelegate.pumps.count; ++endIdx) {
		Gas *gas = (Gas *)[appDelegate.pumps objectAtIndex:endIdx];
		NSComparisonResult comp = [endDate compare:gas.date];
		if (comp == NSOrderedSame || comp == NSOrderedDescending) break;
	}
	if (beginIdx < 0 || endIdx == appDelegate.pumps.count || endIdx >= beginIdx) {
		[self showErrorText:@"There are no fill-ups between the selected dates."];
		goto error;
	}
	Gas *beginGas = (Gas *)[appDelegate.pumps objectAtIndex:beginIdx];
	Gas *endGas = (Gas *)[appDelegate.pumps objectAtIndex:endIdx];
	if (beginGas.odometer >= endGas.odometer) {
		[self showErrorText:@"The car had not been driven between the selected dates."];
		goto error;
	}
	totalDistance = endGas.odometer - beginGas.odometer;
	int firstFillIdx = -1, lastFillIdx = -1;
	for (int i = beginIdx; i >= endIdx; --i) {
		Gas *gas = (Gas *)[appDelegate.pumps objectAtIndex:i];
		if (gas.full) {
			fillCount++;
			lastFillIdx = i;
			if (firstFillIdx == -1) {
				firstFillIdx = i;
			}
		}
		totalFuel += gas.volume;
		totalCost += gas.cost;
	}
	
	float fuelDenom = 0.0, costNumer = 0.0, distanceStat = 0.0;
	Gas *firstFillGas = (Gas *)[appDelegate.pumps objectAtIndex:firstFillIdx];
	Gas *lastFillGas = (Gas *)[appDelegate.pumps objectAtIndex:lastFillIdx];
	distanceStat = lastFillGas.odometer - firstFillGas.odometer;
	if (fillCount > 1 && distanceStat >= 0.0) {
		for (int i = firstFillIdx - 1; i >= lastFillIdx; --i) {
			Gas *gas = (Gas *)[appDelegate.pumps objectAtIndex:i];
			fuelDenom += gas.volume;
			costNumer += gas.cost;
		}
	}
	
	if (fuelDenom > 0) {
		dpf = distanceStat / fuelDenom;
		int prefUnits = [FuelLogAppDelegate pref].units;
		if (dpf > 0.0 && prefUnits == INV_METRIC) {
			dpf = 100.0 / dpf;
		} else if (dpf > 0.0 && prefUnits == NORWAY) {
			dpf = 10.0 / dpf;
		} else if ([FuelLogAppDelegate pref].units == UK) {
			dpf = dpf * UK_GALLON;
		}
	}
	if (distanceStat > 0) cpd = costNumer / distanceStat;
	[self setDistanceString:[[FuelLogAppDelegate pref].distanceFormatter stringFromNumber:[NSNumber numberWithFloat:totalDistance]]];
	NSString *fuel = [[FuelLogAppDelegate pref].volumeFormatter stringFromNumber:[NSNumber numberWithFloat:totalFuel]];
	if (NO && [FuelLogAppDelegate pref].units == UK) {
		NSString *fuelConverted = [[FuelLogAppDelegate pref].volumeFormatter stringFromNumber:[NSNumber numberWithFloat:totalFuel*UK_GALLON]];
		[self setVolumeString:[NSString stringWithFormat:@"%@ (%@G)", fuel, fuelConverted]];
	} else {
		[self setVolumeString:fuel];
	}
	[self setConsumptionString:[[FuelLogAppDelegate pref].volumeFormatter stringFromNumber:[NSNumber numberWithFloat:dpf]]];
	[self setCostString:[[FuelLogAppDelegate pref].costFormatter stringFromNumber:[NSNumber numberWithFloat:totalCost]]];
	[self setCostDistanceString:[[FuelLogAppDelegate pref].costFormatter stringFromNumber:[NSNumber numberWithFloat:cpd]]];
	
	if (fillCount < 3) {
		[self showErrorText:@"3 or more full-tanks are needed to plot fuel efficiency."];
		goto noplot;
	}
	/*
	else {
		CGRect rect = CGRectMake(20.0, 270.0, 280.0, 175.0);
		if (quartzView && quartzView.superview) {
			[quartzView removeFromSuperview];
			[quartzView.delegate release];
			[quartzView release];
			quartzView = nil;
		}
		quartzView = [[QuartzView alloc] initWithFrame:rect];
		Plot *plot = [Plot alloc];
		plot.beginIdx = beginIdx;
		plot.endIdx = endIdx;
		quartzView.delegate = plot;
		[self.view addSubview:quartzView];
	}*/
	return;
	
error:
	if (quartzView) {
		[quartzView removeFromSuperview];
		[quartzView.delegate release];
		[quartzView release];
		quartzView = nil;
	}
	[self.view setNeedsDisplayInRect:CGRectMake(20.0, 270.0, 280.0, 175.0)];
	[self setDistanceString:[[FuelLogAppDelegate pref].distanceFormatter stringFromNumber:[NSNumber numberWithFloat:0.0]]];
	[self setVolumeString:[[FuelLogAppDelegate pref].volumeFormatter stringFromNumber:[NSNumber numberWithFloat:0.0]]];
	[self setConsumptionString:[[FuelLogAppDelegate pref].volumeFormatter stringFromNumber:[NSNumber numberWithFloat:0.0]]];
	[self setCostString:[[FuelLogAppDelegate pref].costFormatter stringFromNumber:[NSNumber numberWithFloat:0.0]]];
	[self setCostDistanceString:[[FuelLogAppDelegate pref].costFormatter stringFromNumber:[NSNumber numberWithFloat:0.0]]];
	return;
	
noplot:
	if (quartzView) {
		[quartzView removeFromSuperview];
		[quartzView.delegate release];
		[quartzView release];
		quartzView = nil;
	}
	return;
}
#pragma mark end setupBoxes
#pragma mark -

#pragma mark Init and View

- (id)initWithStyle:(UITableViewStyle)style {
    if (self = [super initWithStyle:style]) {
		doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
																   target:self
																   action:@selector(done:)];
		self.navigationItem.rightBarButtonItem = doneButton;
    }
	
	preferencesPrimaryArray = [[NSArray alloc] initWithObjects:
							   [NSString stringWithString:(NSLocalizedString(@"last 10 refills", @"last 10 refills "))],
							   [NSString stringWithString:(NSLocalizedString(@"last 3 month", @"last 3 month"))],
							   [NSString stringWithString:(NSLocalizedString(@"last 6 month", @"last 6 month"))],
							   [NSString stringWithString:(NSLocalizedString(@"last year", @"last year"))],
							   [NSString stringWithString:(NSLocalizedString(@"all entries", @"all entries"))],
							   nil];
	preferencesSecondaryArray = [[NSArray alloc] initWithObjects:
								 [NSString stringWithString:@" "],
								 [NSString stringWithString:@" "],
								 [NSString stringWithString:@" "],
								 [NSString stringWithString:@" "],
								 [NSString stringWithString:@" "],
								 nil];
	preferencesTitleArray = [[NSArray alloc] initWithObjects:
							 [NSString stringWithString:(NSLocalizedString(@"Period", @"Period"))],
							 nil];
	
 	return self;
}




/*
 - (void)viewDidLoad {
 [super viewDidLoad];
 
 // Uncomment the following line to preserve selection between presentations.
 self.clearsSelectionOnViewWillAppear = NO;
 
 // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
 // self.navigationItem.rightBarButtonItem = self.editButtonItem;
 }
 */


- (void)viewWillAppear:(BOOL)animated {
	debug(@"in viewWillAppear");
	[(UIScrollView*)[self view] setScrollEnabled:YES];
	[self.navigationController setToolbarHidden:YES animated:YES];
	[super viewWillAppear:animated];
	//	quartzView = nil;
	FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	if (appDelegate.pumps.count > 0) {
		[self setBeginDate:((Gas *)[appDelegate.pumps objectAtIndex:0]).date];
		[self setEndDate:((Gas *)[appDelegate.pumps objectAtIndex:appDelegate.pumps.count - 1]).date];
	} else {
		[self setBeginDate:[FuelLogAppDelegate getNoonUTC:[NSDate date]]];
		[self setEndDate:[FuelLogAppDelegate getNoonUTC:[NSDate date]]];
	}
	
	[self setBoxes];
}

/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 }
 */
/*
 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 }
 */
/*
 - (void)viewDidDisappear:(BOOL)animated {
 [super viewDidDisappear:animated];
 }
 */
/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */


#pragma mark -
#pragma mark Table view data source
/*
 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
 {
 //CGFloat hightForRow = (480 - 44) / (float)[primaryLabelStringArray count];
 return 50; //hightForRow;
 }
 // */


 - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ 
 NSString * returnValue = @"";
/* FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
 if (appDelegate.currentCar) {
 returnValue = appDelegate.currentCar.label;
 }*/
	 
	 switch (section) {
		 case stats_SectionSetup:
			 returnValue = (NSLocalizedString(@"Observation Period", @"Observation Period"));
			 break;
			 case stats_SectionData:
			 returnValue = (NSLocalizedString(@"Results", @"Results"));
				 break;
		 case stats_SectionView:
			 returnValue = (NSLocalizedString(@"Graphs", @"Graphs"));
			 break;
			 
		 default:
			 break;
	 }
 return  returnValue;
 }


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
	NSInteger returnValue = stats_NumberofSections;
	if (fillCount <3) returnValue--; // suppress graph cells if less than three refills
    return returnValue;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
	NSInteger returnValue = 0;
	if (section == stats_SectionSetup ) returnValue = stats_NumberOfRowsSectionSetup;
	switch (section) {
		case stats_SectionSetup:
			returnValue = stats_NumberOfRowsSectionSetup;
			break;
		case stats_SectionData:
			returnValue = stats_NumberOfRowsSectionData;
			break;
		default:
			returnValue = stats_NumberOfRowsSectionView;
			break;
	} 
    return returnValue;
}


// Customize the appearance of table view cells.

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *CellIdentifier = @"CellIdentifier";
	//debug(@"section %d, row %d", indexPath.section, indexPath.row);
	UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil)  cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
	cell.accessoryType=UITableViewCellAccessoryNone;
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
	if (indexPath.section == stats_SectionSetup) {
		switch (indexPath.row) {
			case stats_ObservationPeriod: // simple cell used as a button
				cell.textLabel.text = (NSLocalizedString(@"Observation Period", @"Observation Period"));
				cell.detailTextLabel.text = self.dateString;
				cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
				cell.selectionStyle = UITableViewCellSelectionStyleBlue;
				break;
			case stats_BeginDate: 
				cell.textLabel.text = (NSLocalizedString(@"Begin Date", @"Begin Date"));
				cell.detailTextLabel.text = self.beginDateString ;
				cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
				cell.selectionStyle = UITableViewCellSelectionStyleBlue;
				break;
			case stats_EndDate: 
				cell.textLabel.text = (NSLocalizedString(@"End Date", @"End Date"));
				cell.detailTextLabel.text = self.endDateString ;
				cell.selectionStyle = UITableViewCellSelectionStyleBlue;
				cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
				break;
		}
	}
	if (indexPath.section == stats_SectionData) {
		switch (indexPath.row) {
			case stats_Distance: 
				cell.textLabel.text = [FuelLogAppDelegate pref].distanceText ; // (NSLocalizedString(@"Distance", @"Distance"));
				cell.detailTextLabel.text =  self.distanceString;
				break;
			case stats_Volume: 
				cell.textLabel.text = [FuelLogAppDelegate pref].fuelText; //(NSLocalizedString(@"Distance", @"Distance"));
				cell.detailTextLabel.text =  self.volumeString;
				break;
			case stats_Consumption: 
				cell.textLabel.text = [FuelLogAppDelegate pref].dpfText; //(NSLocalizedString(@"Consumption", @"Consumption"));
				cell.detailTextLabel.text =  self.consumptionString;
				break;
			case stats_Cost: 
				cell.textLabel.text = (NSLocalizedString(@"Cost", @"Cost"));
				cell.detailTextLabel.text = self.costString ;
				break;
			case stats_CostPerDistance: 
				cell.textLabel.text = [FuelLogAppDelegate pref].cpdText; // (NSLocalizedString(@"CostPerDistance", @"CostPerDistance"));
				cell.detailTextLabel.text =  self.costDistanceString;
				break;
				
			default:
				break;
		}
	}
	if (indexPath.section == stats_SectionView) {
		switch (indexPath.row) {
			case stats_SectionView_RowPlot: 
				cell.textLabel.text = (NSLocalizedString(@"View Plot Chart", @"View Plot Chart"));
				break;
			case stats_SectionView_RowBar: 
				cell.textLabel.text = (NSLocalizedString(@"View Bar Chart", @"View Bar Chart"));
				break;
			default:
				break;
		}
		cell.detailTextLabel.text = @"";
		cell.textLabel.textAlignment = UITextAlignmentCenter; 
		cell.selectionStyle = UITableViewCellSelectionStyleBlue;
	}
	return cell;
}


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


#pragma mark -
#pragma mark Table view delegate


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	debug(@"selected cell section %d, Row: %d",indexPath.section, indexPath.row);
	if (indexPath.section == stats_SectionSetup) {
		switch (indexPath.row) {
			case stats_ObservationPeriod: 
				prefsNumericSubViewController = [[PrefsNumericSubViewController alloc] initWithStyle:UITableViewStyleGrouped];
				[prefsNumericSubViewController setPreferencesPrimaryArray:preferencesPrimaryArray ];
				[prefsNumericSubViewController setPreferencesSecondaryArray:preferencesSecondaryArray];
				[prefsNumericSubViewController setPreferencesTitleArray:[preferencesTitleArray objectAtIndex:0]];
				[prefsNumericSubViewController setIndicatorForPreferenceToWorkOn:statsRow_ObservationPeriod];
				[self.navigationController pushViewController:prefsNumericSubViewController animated:YES];
				break;
			default:
				break;
		}
	}	
	if (indexPath.section == stats_SectionView) {
		switch (indexPath.row) {
			case stats_SectionView_RowPlot:
				plotV2ViewController = [[PlotV2ViewController alloc] init]; 
				[plotV2ViewController setBeginIdx:beginIdx];
				[plotV2ViewController setEndIdx:endIdx];

				[self.navigationController pushViewController:plotV2ViewController animated:NO];
				// No animation, ... it's a bit slow on the 3G
				break;
				case stats_SectionView_RowBar:
				barGraphViewController = [[BarGraphViewController alloc] init]; 
				[self.navigationController pushViewController:barGraphViewController animated:NO];
				// No animation, ... it's a bit slow on the 3G
					break;

			default:
				break;
		}
	}
	//	if ((indexPath.section == 1) && (indexPath.row == 0)){
	//		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Delete this entry?"
	//													   delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Yes, Delete", nil];
	//		[alert show];
	//		[alert release];
	//	}
	[tableView deselectRowAtIndexPath:indexPath animated:NO];
	[tableView reloadData];
	
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
	debug(@"selected cell section %d, Row: %d",indexPath.section, indexPath.row);
}
/*
 - (void)actionFlipRowState:(id)sender {
 UISwitch *tempSwitch = (UISwitch *)sender;
 fullTankIndicator = tempSwitch.on;
 debug(@"in actionFlipRowState: %d , %d", fullTankIndicator, tempSwitch.on);
 }*/
#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	[doneButton release]; 
	[dateString release];
	[distanceString release];
	[volumeString release];
	[consumptionString release];
	[costString release];
	[costDistanceString release];
	
	[unitCostString release];
	
	
    [super dealloc];
}


@end

